/**
 * 公告公示管理页面
 * 
 * 管理公告公示内容
 */
import React, { useState } from 'react';
import { toast } from 'sonner';
import AdminLayout from '@/components/admin/AdminLayout';
import ImageUpload from '@/components/common/ImageUpload';
import SimpleRichTextEditor from '@/components/common/SimpleRichTextEditor';
import { useAnnouncements, useCreateAnnouncement, useUpdateAnnouncement, useDeleteAnnouncement, useToggleAnnouncementStatus } from '@/hooks/useAnnouncements';
import { useQueryClient } from '@tanstack/react-query';
import { Announcement, AnnouncementCreate, AnnouncementUpdate } from '@/types';

// 公告分类选项
const ANNOUNCEMENT_CATEGORIES = [
  { value: '资质公示', label: '资质公示' },
  { value: '监测公示', label: '监测公示' },
  { value: '项目公示', label: '项目公示' },
  { value: '政策公示', label: '政策公示' },
];

export default function AnnouncementManagement() {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isViewModalOpen, setIsViewModalOpen] = useState(false);
  const [currentAnnouncement, setCurrentAnnouncement] = useState<Announcement | null>(null);
  const [isEditing, setIsEditing] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const [categoryFilter, setCategoryFilter] = useState('');
  const [statusFilter, setStatusFilter] = useState('');
  const [selectedItems, setSelectedItems] = useState<number[]>([]);
  const [showBatchActions, setShowBatchActions] = useState(false);

  const queryClient = useQueryClient();

  // 使用API hooks
  const { data: announcementsData, isLoading, error } = useAnnouncements({
    keyword: searchTerm,
    category: categoryFilter,
    published_only: false, // 获取所有状态
    page: 1,
    size: 50
  });

  const createAnnouncementMutation = useCreateAnnouncement();
  const updateAnnouncementMutation = useUpdateAnnouncement();
  const deleteAnnouncementMutation = useDeleteAnnouncement();
  const toggleStatusMutation = useToggleAnnouncementStatus();
  
  // 表单状态
  const [formData, setFormData] = useState({
    title: '',
    excerpt: '',
    content: '',
    cover_image: '',
    category: '资质公示',
    is_published: false
  });

  // 筛选公告
  const filteredAnnouncements = (announcementsData?.items || []).filter(announcement => {
    // 状态筛选
    if (statusFilter === 'published' && !announcement.is_published) return false;
    if (statusFilter === 'draft' && announcement.is_published) return false;
    return true;
  });

  // 打开新建模态框
  const openModal = () => {
    setIsModalOpen(true);
    setIsEditing(false);
    setCurrentAnnouncement(null);
    setFormData({
      title: '',
      excerpt: '',
      content: '',
      cover_image: '',
      category: '资质公示',
      is_published: false
    });
  };

  // 打开编辑模态框
  const openEditModal = (announcement: Announcement) => {
    setIsModalOpen(true);
    setIsEditing(true);
    setCurrentAnnouncement(announcement);
    setFormData({
      title: announcement.title,
      excerpt: announcement.excerpt || '',
      content: announcement.content,
      cover_image: announcement.cover_image || '',
      category: announcement.category,
      is_published: announcement.is_published
    });
  };

  // 关闭模态框
  const closeModal = () => {
    setIsModalOpen(false);
    setCurrentAnnouncement(null);
    setIsEditing(false);
  };

  // 打开查看模态框
  const openViewModal = (announcement: Announcement) => {
    setCurrentAnnouncement(announcement);
    setIsViewModalOpen(true);
  };

  // 关闭查看模态框
  const closeViewModal = () => {
    setIsViewModalOpen(false);
    setCurrentAnnouncement(null);
  };

  // 处理表单提交
  const handleSubmit = async (e: React.FormEvent, publishNow: boolean = false) => {
    e.preventDefault();

    if (!formData.title.trim()) {
      toast.error('请输入公告标题');
      return;
    }

    if (!formData.content.trim()) {
      toast.error('请输入公告内容');
      return;
    }

    const announcementData: AnnouncementCreate | AnnouncementUpdate = {
      title: formData.title,
      excerpt: formData.excerpt,
      content: formData.content,
      cover_image: formData.cover_image,
      category: formData.category,
      is_published: publishNow
    };

    try {
      if (isEditing && currentAnnouncement) {
        await updateAnnouncementMutation.mutateAsync({
          id: currentAnnouncement.id,
          data: announcementData as AnnouncementUpdate
        });
        toast.success(publishNow ? '公告已发布' : '草稿已保存');
      } else {
        await createAnnouncementMutation.mutateAsync(announcementData as AnnouncementCreate);
        toast.success(publishNow ? '公告已发布' : '草稿已保存');
      }

      // 强制刷新数据
      queryClient.invalidateQueries({
        queryKey: ['announcements'],
        exact: false
      });

      closeModal();
    } catch (error) {
      toast.error(publishNow ? '发布失败' : '保存失败');
    }
  };

  // 切换发布状态
  const togglePublishStatus = async (id: number, currentStatus: boolean) => {
    try {
      await toggleStatusMutation.mutateAsync({
        id,
        is_published: !currentStatus
      });
      toast.success(currentStatus ? '已取消发布' : '已发布');
    } catch (error) {
      toast.error('操作失败');
    }
  };

  // 删除公告
  const deleteAnnouncement = async (id: number) => {
    if (!confirm('确定要删除这条公告吗？')) return;

    try {
      await deleteAnnouncementMutation.mutateAsync(id);
      toast.success('公告已删除');
    } catch (error) {
      toast.error('删除失败');
    }
  };

  // 批量操作函数
  const handleSelectAll = (checked: boolean) => {
    if (checked) {
      setSelectedItems(filteredAnnouncements.map(item => item.id));
    } else {
      setSelectedItems([]);
    }
  };

  const handleSelectItem = (id: number, checked: boolean) => {
    if (checked) {
      setSelectedItems(prev => [...prev, id]);
    } else {
      setSelectedItems(prev => prev.filter(item => item !== id));
    }
  };

  const handleBatchPublish = async () => {
    if (selectedItems.length === 0) return;

    if (!confirm(`确定要发布选中的 ${selectedItems.length} 条公告吗？`)) return;

    try {
      await Promise.all(
        selectedItems.map(id =>
          toggleStatusMutation.mutateAsync({ id, is_published: true })
        )
      );
      toast.success(`已发布 ${selectedItems.length} 条公告`);
      setSelectedItems([]);
    } catch (error) {
      toast.error('批量发布失败');
    }
  };

  const handleBatchDelete = async () => {
    if (selectedItems.length === 0) return;

    if (!confirm(`确定要删除选中的 ${selectedItems.length} 条公告吗？此操作不可恢复！`)) return;

    try {
      await Promise.all(
        selectedItems.map(id => deleteAnnouncementMutation.mutateAsync(id))
      );
      toast.success(`已删除 ${selectedItems.length} 条公告`);
      setSelectedItems([]);
    } catch (error) {
      toast.error('批量删除失败');
    }
  };

  if (isLoading) {
    return (
      <AdminLayout>
        <div className="flex items-center justify-center min-h-[500px]">
          <div className="text-center">
            <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
            <p className="text-gray-600">加载中...</p>
          </div>
        </div>
      </AdminLayout>
    );
  }

  if (error) {
    return (
      <AdminLayout>
        <div className="flex items-center justify-center min-h-[500px]">
          <div className="text-center">
            <p className="text-red-600 mb-4">加载失败</p>
            <button
              type="button"
              onClick={() => window.location.reload()}
              className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
            >
              重新加载
            </button>
          </div>
        </div>
      </AdminLayout>
    );
  }

  return (
    <AdminLayout>
      <div className="space-y-6">
        {/* 页面头部 */}
        <div className="flex items-center justify-between">
          <div>
            <h1 className="text-2xl font-bold text-gray-800">公告公示管理</h1>
            <p className="text-gray-600">
              管理公司公告公示内容
              <span className="ml-4 text-sm">
                <span className="text-green-600">已发布: {(announcementsData?.items || []).filter(a => a.is_published).length}</span>
                <span className="ml-3 text-orange-600">草稿: {(announcementsData?.items || []).filter(a => !a.is_published).length}</span>
              </span>
            </p>
          </div>
          <button
            type="button"
            onClick={openModal}
            className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors flex items-center space-x-2"
          >
            <i className="fa-solid fa-plus text-sm"></i>
            <span>添加公告</span>
          </button>
        </div>

        {/* 搜索和筛选 */}
        <div className="bg-white p-6 rounded-lg shadow-sm border">
          <div className="flex flex-col md:flex-row md:items-center md:justify-between space-y-4 md:space-y-0 md:space-x-4">
            <div className="flex-1">
              <input
                type="text"
                placeholder="搜索公告标题..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="w-full px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
              />
            </div>
            <div className="flex space-x-4">
              <select
                value={categoryFilter}
                onChange={(e) => setCategoryFilter(e.target.value)}
                className="px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
              >
                <option value="">所有分类</option>
                {ANNOUNCEMENT_CATEGORIES.map(category => (
                  <option key={category.value} value={category.value}>
                    {category.label}
                  </option>
                ))}
              </select>
              <select
                value={statusFilter}
                onChange={(e) => setStatusFilter(e.target.value)}
                className="px-4 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
              >
                <option value="">全部状态</option>
                <option value="published">已发布</option>
                <option value="draft">草稿</option>
              </select>
              <button
                type="button"
                onClick={() => {
                  setSearchTerm('');
                  setCategoryFilter('');
                  setStatusFilter('');
                }}
                className="px-4 py-2 text-gray-600 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
              >
                重置
              </button>
            </div>
          </div>
        </div>

        {/* 批量操作栏 */}
        {selectedItems.length > 0 && (
          <div className="bg-blue-50 border border-blue-200 rounded-lg p-4">
            <div className="flex items-center justify-between">
              <div className="flex items-center space-x-4">
                <span className="text-sm font-medium text-blue-900">
                  已选择 {selectedItems.length} 项
                </span>
                <button
                  type="button"
                  onClick={() => setSelectedItems([])}
                  className="text-sm text-blue-600 hover:text-blue-800"
                >
                  取消选择
                </button>
              </div>
              <div className="flex items-center space-x-3">
                <button
                  type="button"
                  onClick={handleBatchPublish}
                  className="px-4 py-2 bg-green-600 text-white text-sm rounded-lg hover:bg-green-700 transition-colors"
                >
                  批量发布
                </button>
                <button
                  type="button"
                  onClick={handleBatchDelete}
                  className="px-4 py-2 bg-red-600 text-white text-sm rounded-lg hover:bg-red-700 transition-colors"
                >
                  批量删除
                </button>
              </div>
            </div>
          </div>
        )}

        {/* 公告列表 */}
        <div className="bg-white rounded-lg shadow-sm border overflow-hidden">
          {filteredAnnouncements.length === 0 ? (
            <div className="text-center py-12">
              <i className="fa-solid fa-bullhorn text-4xl text-gray-300 mb-4"></i>
              <p className="text-gray-500 text-lg mb-2">暂无公告</p>
              <p className="text-gray-400 text-sm">点击"添加公告"开始创建公告</p>
            </div>
          ) : (
            <div className="overflow-x-auto">
              <table className="min-w-full divide-y divide-gray-200">
                <thead className="bg-gray-50">
                  <tr>
                    <th className="px-6 py-3 text-left">
                      <input
                        type="checkbox"
                        checked={selectedItems.length === filteredAnnouncements.length && filteredAnnouncements.length > 0}
                        onChange={(e) => handleSelectAll(e.target.checked)}
                        className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                      />
                    </th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">ID</th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">图片</th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">标题</th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">分类</th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">状态</th>
                    <th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">创建时间</th>
                    <th className="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">操作</th>
                  </tr>
                </thead>
                <tbody className="bg-white divide-y divide-gray-200">
                  {filteredAnnouncements.map((announcement) => (
                    <tr key={announcement.id} className="hover:bg-gray-50">
                      <td className="px-6 py-4 whitespace-nowrap">
                        <input
                          type="checkbox"
                          checked={selectedItems.includes(announcement.id)}
                          onChange={(e) => handleSelectItem(announcement.id, e.target.checked)}
                          className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                        />
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900">{announcement.id}</td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        {announcement.cover_image ? (
                          <img 
                            src={announcement.cover_image} 
                            alt={announcement.title}
                            className="h-12 w-12 object-cover rounded"
                          />
                        ) : (
                          <div className="h-12 w-12 bg-gray-200 rounded flex items-center justify-center">
                            <i className="fa-solid fa-image text-gray-400"></i>
                          </div>
                        )}
                      </td>
                      <td className="px-6 py-4">
                        <div className="text-sm font-medium text-gray-900">{announcement.title}</div>
                        {announcement.excerpt && (
                          <div className="text-sm text-gray-500 mt-1 line-clamp-2">{announcement.excerpt}</div>
                        )}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800">
                          {announcement.category}
                        </span>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium ${
                          announcement.is_published 
                            ? 'bg-green-100 text-green-800' 
                            : 'bg-orange-100 text-orange-800'
                        }`}>
                          {announcement.is_published ? '已发布' : '草稿'}
                        </span>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500">{announcement.created_at}</td>
                      <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                        <button
                          type="button"
                          onClick={() => openViewModal(announcement)}
                          className="text-gray-600 hover:text-gray-900 mr-3 text-sm"
                        >
                          查看
                        </button>
                        <button
                          type="button"
                          onClick={() => togglePublishStatus(announcement.id, announcement.is_published)}
                          className={`mr-3 text-sm ${
                            announcement.is_published
                              ? 'text-orange-600 hover:text-orange-900'
                              : 'text-green-600 hover:text-green-900'
                          }`}
                        >
                          {announcement.is_published ? '取消发布' : '发布'}
                        </button>
                        <button
                          type="button"
                          onClick={() => openEditModal(announcement)}
                          className="text-blue-600 hover:text-blue-900 mr-3 text-sm"
                        >
                          编辑
                        </button>
                        <button
                          type="button"
                          onClick={() => deleteAnnouncement(announcement.id)}
                          className="text-red-600 hover:text-red-900 text-sm"
                        >
                          删除
                        </button>
                      </td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          )}
        </div>
      </div>

      {/* 新建/编辑模态框 */}
      {isModalOpen && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
          <div className="bg-white rounded-lg max-w-4xl w-full max-h-[90vh] overflow-y-auto">
            <div className="p-6 border-b">
              <div className="flex items-center justify-between">
                <h3 className="text-lg font-bold text-gray-800">{isEditing ? '编辑公告' : '添加公告'}</h3>
                <button
                  type="button"
                  onClick={closeModal}
                  className="text-gray-500 hover:text-gray-700"
                >
                  <i className="fa-solid fa-times text-xl"></i>
                </button>
              </div>
            </div>
            
            <form onSubmit={(e) => handleSubmit(e, false)} className="p-6 space-y-6">
              {/* 基本信息 */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    公告标题 <span className="text-red-500">*</span>
                  </label>
                  <input
                    type="text"
                    value={formData.title}
                    onChange={(e) => setFormData({ ...formData, title: e.target.value })}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                    placeholder="请输入公告标题"
                    required
                  />
                </div>
                
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    公告分类
                  </label>
                  <select
                    value={formData.category}
                    onChange={(e) => setFormData({ ...formData, category: e.target.value })}
                    className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  >
                    {ANNOUNCEMENT_CATEGORIES.map(category => (
                      <option key={category.value} value={category.value}>
                        {category.label}
                      </option>
                    ))}
                  </select>
                </div>
              </div>

              {/* 封面图片 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  封面图片
                </label>
                <ImageUpload
                  value={formData.cover_image}
                  onChange={(url) => setFormData({ ...formData, cover_image: url })}
                  className="w-full"
                />
              </div>

              {/* 公告摘要 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  公告摘要
                </label>
                <textarea
                  value={formData.excerpt}
                  onChange={(e) => setFormData({ ...formData, excerpt: e.target.value })}
                  rows={3}
                  className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                  placeholder="请输入公告摘要（可选）"
                />
              </div>

              {/* 公告内容 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  公告内容 <span className="text-red-500">*</span>
                </label>
                <SimpleRichTextEditor
                  value={formData.content}
                  onChange={(content) => setFormData({ ...formData, content })}
                  placeholder="请输入公告内容"
                  height={400}
                />
              </div>

              {/* 操作按钮 */}
              <div className="flex justify-end space-x-4 pt-6 border-t">
                <button
                  type="button"
                  onClick={closeModal}
                  className="px-6 py-2 text-gray-600 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
                >
                  取消
                </button>
                <button
                  type="submit"
                  className="px-6 py-2 bg-gray-600 text-white rounded-lg hover:bg-gray-700 transition-colors"
                >
                  保存草稿
                </button>
                <button
                  type="button"
                  onClick={(e) => handleSubmit(e, true)}
                  className="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
                >
                  发布
                </button>
              </div>
            </form>
          </div>
        </div>
      )}

      {/* 查看详情模态框 */}
      {isViewModalOpen && currentAnnouncement && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50">
          <div className="bg-white rounded-lg max-w-4xl w-full max-h-[90vh] overflow-y-auto">
            <div className="p-6 border-b">
              <div className="flex items-center justify-between">
                <h3 className="text-lg font-bold text-gray-800">查看公告详情</h3>
                <button
                  type="button"
                  onClick={closeViewModal}
                  className="text-gray-500 hover:text-gray-700"
                >
                  <i className="fa-solid fa-times text-xl"></i>
                </button>
              </div>
            </div>

            <div className="p-6 space-y-6">
              {/* 基本信息 */}
              <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">公告标题</label>
                  <div className="text-lg font-semibold text-gray-900">{currentAnnouncement.title}</div>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">公告分类</label>
                  <span className="inline-flex items-center px-2.5 py-0.5 rounded-full text-sm font-medium bg-blue-100 text-blue-800">
                    {currentAnnouncement.category}
                  </span>
                </div>
              </div>

              {/* 状态信息 */}
              <div className="grid grid-cols-1 md:grid-cols-3 gap-6">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">发布状态</label>
                  <span className={`inline-flex items-center px-2.5 py-0.5 rounded-full text-sm font-medium ${
                    currentAnnouncement.is_published
                      ? 'bg-green-100 text-green-800'
                      : 'bg-orange-100 text-orange-800'
                  }`}>
                    {currentAnnouncement.is_published ? '已发布' : '草稿'}
                  </span>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">创建时间</label>
                  <div className="text-sm text-gray-900">
                    {new Date(currentAnnouncement.created_at).toLocaleString('zh-CN')}
                  </div>
                </div>

                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">浏览次数</label>
                  <div className="text-sm text-gray-900">{currentAnnouncement.view_count || 0} 次</div>
                </div>
              </div>

              {/* 封面图片 */}
              {currentAnnouncement.cover_image && (
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">封面图片</label>
                  <img
                    src={currentAnnouncement.cover_image}
                    alt={currentAnnouncement.title}
                    className="max-w-md h-auto rounded-lg border"
                  />
                </div>
              )}

              {/* 公告摘要 */}
              {currentAnnouncement.excerpt && (
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">公告摘要</label>
                  <div className="text-gray-900 bg-gray-50 p-4 rounded-lg">
                    {currentAnnouncement.excerpt}
                  </div>
                </div>
              )}

              {/* 公告内容 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">公告内容</label>
                <div
                  className="prose max-w-none bg-gray-50 p-4 rounded-lg"
                  dangerouslySetInnerHTML={{ __html: currentAnnouncement.content }}
                />
              </div>

              {/* 操作按钮 */}
              <div className="flex justify-end space-x-4 pt-6 border-t">
                <button
                  type="button"
                  onClick={closeViewModal}
                  className="px-6 py-2 text-gray-600 border border-gray-300 rounded-lg hover:bg-gray-50 transition-colors"
                >
                  关闭
                </button>
                <button
                  type="button"
                  onClick={() => {
                    closeViewModal();
                    openEditModal(currentAnnouncement);
                  }}
                  className="px-6 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors"
                >
                  编辑公告
                </button>
              </div>
            </div>
          </div>
        </div>
      )}
    </AdminLayout>
  );
}
